<template>
  <el-dialog
    :model-value="dialogAdd"
    width="40%"
    title="空间详情-添加"
    :before-close="handleClose"
  >
    <el-divider />

    <!-- 添加表单内容 -->
    <el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
      <el-form-item label="空间名称：" prop="name">
        <div class="space-info-row">
          <SearchInput
            ref="searchInputRef"
            v-model="form.name"
            style="width: 420px"
            placeholder="请输入空间名称"
            :search-api="searchSpaces"
            @select="handleSpaceSelect"
            :search-data="newResponse"
            :disabled="disabledInput"
            @input="handleNameInput"
          />
          <CitySelect
            ref="citySelectRef"
            v-model="form.city"
            @cityChange="handleCityChange"
            @cityValue="handleCityValue"
            style="width: 180px"
            :is-error="citySelectError"
          />
        </div>
      </el-form-item>
      <el-form-item label="空间地址：" prop="destName">
        <el-input
          v-model="form.destName"
          disabled
          placeholder="选择空间名称后自动填入"
        />
      </el-form-item>
      <el-form-item label="地点坐标：" prop="destLongitude">
        <el-input
          :model-value="coordinates"
          disabled
          placeholder="选择空间名称后自动填入"
        />
      </el-form-item>

      <el-form-item label="封面图片：" prop="coverUrl">
        <el-upload
          class="upload-box"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleCoverChange"
          :on-remove="handleCoverRemove"
          accept="image/jpeg,image/png,image/gif,image/jpg"
        >
          <template v-if="form.coverUrl">
            <img :src="form.coverUrl" class="preview-image" />
            <div class="delete-icon" @click.stop="handleCoverRemove">
              <el-icon><Delete /></el-icon>
            </div>
          </template>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>点击上传</span>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="空间平面：" prop="floorPlanUrl">
        <el-upload
          class="upload-box"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFloorPlanChange"
          :on-remove="handleFloorRemove"
          accept="image/jpeg,image/png,image/gif,image/jpg"
        >
          <template v-if="form.floorPlanUrl">
            <img :src="form.floorPlanUrl" class="preview-image" />
            <div class="delete-icon" @click.stop="handleFloorRemove">
              <el-icon><Delete /></el-icon>
            </div>
          </template>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>点击上传</span>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="空间介绍：" prop="intro">
        <el-input
          v-model="form.intro"
          type="textarea"
          :rows="4"
          placeholder="请输入空间介绍"
        />
      </el-form-item>

      <el-form-item label="排序：" prop="orderLevel">
        <el-input-number
          v-model="form.orderLevel"
          :min="0"
          :precision="2"
          controls-position="right"
        />
        <span style="color: #909399; font-size: 12px; margin-left: 15px">
          数值越大，排序越靠前
        </span>
      </el-form-item>

      <el-form-item label="设施：" prop="facilityIdList">
        <el-select
          v-model="form.facilityIdList"
          placeholder="请选择"
          style="width: 240px"
          multiple
        >
          <el-option
            v-for="item in facilitiesListAll"
            :key="item.facilityId"
            :label="item.name"
            :value="item.facilityId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="视频：" prop="mediaIdList">
        <el-select
          v-model="form.mediaIdList"
          placeholder="请选择"
          style="width: 240px"
          multiple
        >
          <el-option
            v-for="item in videoListAll"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="活动公告：" prop="todayAnnouncement">
        <el-input
          v-model="form.todayAnnouncement"
          type="textarea"
          :rows="4"
          placeholder="请输入活动公告"
        />
      </el-form-item>

      <!-- 二维码信息 -->
      <el-form-item label="加入二维码：">
        <div class="qrcode-wrapper">
          <div class="qrcode-header">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleAddQrcode"
            >
              添加
            </el-button>
          </div>
          <div class="qrcode-section">
            <el-table
              :data="qrcodeData"
              style="width: 100%"
              border
              stripe
              fit
              empty-text="暂无数据"
              show-header
              size="small"
              element-loading-text="Loading..."
              :header-cell-style="{ background: '#e7e1fb' }"
              max-height="200px"
            >
              <el-table-column prop="codeTitle" label="底部文字信息" />
              <el-table-column prop="url" label="二维码图片">
                <template #default="scope">
                  <template v-if="scope.row.url">
                    <el-image
                      :src="scope.row.url"
                      fit="cover"
                      style="width: 50px; height: 50px"
                    />
                  </template>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="state" label="详情">
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    @click="handleQrcodeEdit(scope.row)"
                    size="small"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click="handleQrcodeDelete(scope.row)"
                    size="small"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="状态：" prop="state">
        <el-radio-group v-model="form.state">
          <el-radio :value="0">展示</el-radio>
          <el-radio :value="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <QrcodeEdit_Dialog
    v-model:visible="qrcodeDialogVisible"
    :edit-data="currentEditData"
    :is-edit="isEdit"
    @confirm="handleQrcodeConfirm"
  />
</template>

<script setup>
import { onMounted, ref, onUpdated, computed, nextTick } from 'vue';
import { Plus, Delete } from '@element-plus/icons-vue';
import {
  getAddress,
  getFacilities,
  getVideoList,
  addSpace,
} from '@/api/Venue/space';
import CitySelect from '@/components/CitySelect/index.vue';
import SearchInput from '@/components/SearchInput/index.vue';
import { uploadPic } from '@/api/Upload/upload';
import QrcodeEdit_Dialog from './QrcodeEdit_Dialog.vue';
import { ElMessage } from 'element-plus';

const formRef = ref(null);

const form = ref({
  name: '',
  city: '',
  destName: '',
  province: '',
  destLongitude: '',
  destLatitude: '',
  coverUrl: '',
  floorPlanUrl: '',
  facilityIdList: [],
  mediaIdList: [],
  todayAnnouncement: '',
  intro: '',
  orderLevel: 1,
  state: 0,
});
const disabledInput = ref(true);
const qrcodeData = ref([]);
const coordinates = computed(() => {
  if (form.value.destLongitude && form.value.destLatitude) {
    return `${form.value.destLongitude},${form.value.destLatitude}`;
  }
  return '';
});
const facilitiesListAll = ref([]);
const videoListAll = ref([]);
const newResponse = ref([]);
const addressBackup = ref({});
defineProps({
  dialogAdd: {
    type: Boolean,
  },
});
// 定义 emits，向父组件发送事件
const emit = defineEmits(['confirm', 'cancel']);

// 添加 ref
const searchInputRef = ref(null);
const citySelectRef = ref(null);
const citySelectError = ref(false);
const CityValues = ref([]);
// 添加表单验证规则
const rules = {
  name: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!form.value.city) {
          callback(new Error('请先选择城市'));
        } else if (
          !form.value.destName ||
          !form.value.destLongitude ||
          !form.value.destLatitude
        ) {
          callback(new Error('请从下拉列表中选择一个空间'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
  city: [{ required: true, message: '请选择城市', trigger: 'change' }],
  destName: [{ required: true, message: '请选择空间地址', trigger: 'change' }],
  destLongitude: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!form.value.destLongitude || !form.value.destLatitude) {
          callback(new Error('请选择空间地址以获取坐标'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
  coverUrl: [{ required: true, message: '请上传封面图片', trigger: 'change' }],
  floorPlanUrl: [
    { required: true, message: '请上传空间平面图', trigger: 'change' },
  ],
  intro: [{ required: true, message: '请输入空间介绍', trigger: 'blur' }],
  orderLevel: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
  facilityIdList: [
    { required: true, message: '请选择设施', trigger: 'change' },
  ],
  mediaIdList: [{ required: true, message: '请选择视频', trigger: 'change' }],
  todayAnnouncement: [
    { required: true, message: '请输入活动公告', trigger: 'blur' },
  ],
  state: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

// 处理取消按钮的点击事件
const handleCancel = () => {
  // 重置表单
  formRef.value?.resetFields();
  // 重置城市选择器
  citySelectRef.value?.resetSelect();
  // 重置错误状态
  citySelectError.value = false;
  // 清空其他数据
  qrcodeData.value = [];
  form.value = {
    name: '',
    city: '',
    destName: '',
    province: '',
    destLongitude: '',
    destLatitude: '',
    coverUrl: '',
    floorPlanUrl: '',
    facilityIdList: [],
    mediaIdList: [],
    todayAnnouncement: '',
    intro: '',
    orderLevel: 1,
    state: 0,
  };
  // 重置搜索输入框
  if (searchInputRef.value) {
    searchInputRef.value.clearSearch();
  }
  // 通知父组件关闭弹窗
  emit('cancel');
};

// 修改确认按钮的处理函数
const handleConfirm = () => {
  if (!form.value.city) {
    citySelectError.value = true;
  }

  formRef.value?.validate(async (valid) => {
    if (valid) {
      // 添加二维码验证
      if (qrcodeData.value.length === 0) {
        ElMessage({
          message: '请至少添加一个二维码',
          type: 'warning',
        });
        return;
      }

      Object.assign(form.value, {
        qrCodeList: qrcodeData.value,
        addressBackup: JSON.stringify(addressBackup.value),
      });

      const res = await addSpace({ ...form.value });
      if (res.data.code === 200) {
        ElMessage({
          message: '添加成功',
          type: 'success',
        });
        handleCancel();
        emit('confirm');
      } else {
        ElMessage({
          message: res.data.msg || '添加失败',
          type: 'error',
        });
      }
    } else {
      ElMessage({
        message: '请填写完整所有必填项',
        type: 'warning',
      });
      return false;
    }
  });
};

// 关闭对话框
const handleClose = () => {
  handleCancel(); // 使用相同的清空逻辑
};

// 添加图片格式校验函数
const validateImageType = (file) => {
  const acceptedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
  if (!acceptedTypes.includes(file.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片！');
    return false;
  }
  return true;
};

// 修改封面图片上传处理
const handleCoverChange = async (file) => {
  if (!validateImageType(file.raw)) {
    return;
  }

  const formData = new FormData();
  formData.append('picture', file.raw);
  try {
    const response = await uploadPic(formData);
    if (response.data.code === 200) {
      form.value.coverUrl = response.data.data.url;
      ElMessage.success('上传成功');
      await formRef.value?.validateField('coverUrl');
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  }
};

// 处理封面图片删除
const handleCoverRemove = () => {
  form.value.coverUrl = '';
};

// 修改平面图上传处理
const handleFloorPlanChange = async (file) => {
  if (!validateImageType(file.raw)) {
    return;
  }

  const formData = new FormData();
  formData.append('picture', file.raw);
  try {
    const response = await uploadPic(formData);
    if (response.data.code === 200) {
      form.value.floorPlanUrl = response.data.data.url;
      ElMessage.success('上传成功');
      await formRef.value?.validateField('floorPlanUrl');
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  }
};

// 处理平面图删除
const handleFloorRemove = () => {
  form.value.floorPlanUrl = '';
};

// 处理城市选择变化
const handleCityChange = (data) => {
  citySelectError.value = false;
  form.value.province = data.province;
  form.value.name = '';
  form.value.destName = '';
  form.value.destLongitude = '';
  form.value.destLatitude = '';
  if (searchInputRef.value) {
    searchInputRef.value.clearSearch();
  }
};
// 处理城市选择
const handleCityValue = (value) => {
  if (value && value.length === 2) {
    disabledInput.value = false;
    // 选择完省市后，触发表单校验
    nextTick(() => {
      formRef.value?.validateField(['city', 'name']);
    });
  } else {
    disabledInput.value = true;
    // 清空相关字段
    form.value.name = '';
    form.value.destName = '';
    form.value.destLongitude = '';
    form.value.destLatitude = '';
    // 重置搜索输入框
    if (searchInputRef.value) {
      searchInputRef.value.clearSearch();
    }
  }
};
// 搜索空间的API调用
const searchSpaces = async (keyword) => {
  try {
    if (!form.value.city) {
      return [];
    }
    const response = await getAddress({
      keyword,
      region: form.value.city,
      region_fix: 1,
    });

    if (response?.data?.data?.data) {
      // 保存完整的响应数据
      newResponse.value = response.data.data.data;
      // 返回处理后的数据结构
      return response.data.data.data.map((item) => ({
        id: item.id,
        title: item.title,
        address: item.address,
        location: item.location,
        lng: item.location?.lng,
        lat: item.location?.lat,
      }));
    }
    return [];
  } catch (error) {
    console.error('搜索空间失败:', error);
    return [];
  }
};

// 修改空间选择处理函数
const handleSpaceSelect = async (item) => {
  try {
    // 先设置表单值，注意这里要使用正确的数据结构
    form.value.name = item.title; // 改用 title 而不是 name
    form.value.destName = item.address;
    form.value.destLongitude = item.location?.lng || item.lng; // 添加兜底
    form.value.destLatitude = item.location?.lat || item.lat; // 添加兜底
    addressBackup.value = item;

    // 等待下一个 tick，确保表单值已更新
    await nextTick();
    // 重新触发验证
    await formRef.value?.validateField('name');
  } catch (error) {
    console.error('空间选择处理失败:', error);
  }
};

// 添加状态控制
const qrcodeDialogVisible = ref(false);

// 添加编辑状态和当前编辑的数据
const isEdit = ref(false);
const currentEditData = ref(null);

// 修改添加二维码的处理函数
const handleAddQrcode = () => {
  isEdit.value = false;
  currentEditData.value = null;
  qrcodeDialogVisible.value = true;
};

// 编辑二维码
const handleQrcodeEdit = (row) => {
  isEdit.value = true;
  currentEditData.value = row;
  qrcodeDialogVisible.value = true;
};

// 删除二维码
const handleQrcodeDelete = (row) => {
  ElMessageBox.confirm('确认删除该二维码信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const index = qrcodeData.value.findIndex((item) => item === row);
      if (index > -1) {
        qrcodeData.value.splice(index, 1);
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
      }
    })
    .catch(() => {});
};

// 修改二维码数据确认处理函数
const handleQrcodeConfirm = (data) => {
  if (isEdit.value && currentEditData.value) {
    // 编辑模式：更新现有数据
    const index = qrcodeData.value.findIndex(
      (item) => item === currentEditData.value
    );
    if (index > -1) {
      qrcodeData.value[index] = { ...data }; // 使用解构赋值创建新对象
    }
  } else {
    // 添加模式：追加新数据
    qrcodeData.value.push({ ...data }); // 使用解构赋值创建新对象
  }
  qrcodeDialogVisible.value = false; // 关闭对话框
};

// 获取设施下拉
const facilitiesList = async () => {
  const response = await getFacilities();
  facilitiesListAll.value = response.data.data;
};

// 获取视频下拉
const videoList = async () => {
  const response = await getVideoList();
  videoListAll.value = response.data.data;
};

// 修改输入处理函数
const handleNameInput = () => {
  // 清空相关字段
  form.value.destName = '';
  form.value.destLongitude = '';
  form.value.destLatitude = '';

  // 立即触发验证，显示提示信息
  formRef.value?.validateField('name');
};

onMounted(() => {
  facilitiesList();
  videoList();
});
onUpdated(() => {});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.destName-input {
  display: flex;
  gap: 10px;
  align-items: center;

  .el-input {
    flex: 1;
  }
}

.upload-box {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409eff;
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
  }

  .upload-placeholder {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    color: #8c8c8c;

    .el-icon {
      font-size: 20px;
      margin-bottom: 8px;
    }

    span {
      display: block;
      font-size: 12px;
    }
  }

  .delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 24px;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
    border-bottom-left-radius: 8px;

    &:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }
  }

  &:hover .delete-icon {
    opacity: 1;
  }
}

.activity-list,
.qrcode-section {
  width: 100%;

  .el-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
}

.qrcode-section {
  width: 100%;

  .qrcode-item {
    text-align: center;

    .qrcode-title {
      margin-bottom: 10px;
      color: #606266;
      font-size: 14px;
    }

    .qrcode-image {
      width: 120px;
      height: 120px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }
  }
}

:deep(.el-dialog__body) {
  padding-top: 10px;
  padding-bottom: 10px;
}

:deep(.el-dialog__header) {
  padding-bottom: 10px;
  margin-right: 0;
}

.space-info-row {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;

  .el-input,
  .city-select {
    flex-shrink: 0;
  }
}

:deep(.el-table) {
  --el-table-border-color: #dcdfe6;
  --el-table-header-bg-color: #f5f7fa;
  width: 100% !important;
}

.qrcode-header {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.qrcode-section {
  width: 100%;

  :deep(.el-table) {
    width: 100% !important;
  }
}

.qrcode-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
}
</style>
